<?php

namespace App\Api\V1\Controllers;

use App\Api\V1\Services\Wechat\WechatService;
use App\Commons\WechatOpenPlatform\WechatOpenPlatformTool;
use App\Http\Controllers\Controller;
use App\Http\Middleware\TerminateTask;
use EasyWeChat\OpenPlatform\Server\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\CacheBridge;

class WechatController extends Controller
{
    protected $config;

    public function __construct()
    {
        $this->config = array_merge(config('wechat.defaults'),config('wechat.open_platform.default'));
    }

    /**
     * 授权事件处理
     * @hideFromAPIDocumentation
     */
    public function notifyAuth(WechatService $service)
    {
        $openPlatform = WechatOpenPlatformTool::getInstance()->getOpenPlatformApp();
        $server = $openPlatform->server;
        $server->push(function ($payload) use ($openPlatform, $service)  {
            //Log::info('WechatController notifyAuth():  payload:' . json_encode($payload));
            if (isset($payload['InfoType'])) {
                switch ($payload['InfoType']) {
                    case Guard::EVENT_AUTHORIZED: // 授权成功
                        TerminateTask::addTaskFnList(function () use ($service, $payload) {
                            $service->authorized($payload);
                        });
                        break;
                    case Guard::EVENT_UPDATE_AUTHORIZED: // 更新授权
                        TerminateTask::addTaskFnList(function () use ($service, $payload) {
                            $service->updateAuthorized($payload);
                        });
//                        $authorizationInfo = $open_platform->handleAuthorize($payload['AuthorizationCode']);
//                        Log::notice('WechatController notifyAuth(): authorizationInfo: ' . json_encode($authorizationInfo));
//                        $app_id = $authorizationInfo['authorization_info']['authorizer_appid'];
//                        $wechat = Wechat::where('app_id', $app_id)->first();
//                        if (!$wechat) {
//                            $wechat = new Wechat();
//                            $is_new = true;
//                        }
//                        $wechat->auth_code = $payload['AuthorizationCode']; // queryauthcode@@@xxx
//                        $wechat->refresh_token = $authorizationInfo['authorization_info']['authorizer_refresh_token'];
//                        $wechat->auth_result = json_encode($authorizationInfo);
//                        $wechat->auth_status = 1;
//                        $wechat->app_id = $app_id;
//                        $wechat->auth_time = DB::raw('NOW()');
//                        $wechat->save();
//                        if ($is_new) {
//                            event(new WechatAuthorizedEvent($app_id));
//                        } else {
//                            Log::notice("WechatController notifyAuth(): update  auth info for authorizer: [$app_id]: " . json_encode($authorizationInfo));
//                        }
                        break;
                    case Guard::EVENT_UNAUTHORIZED: //取消授权的同时，删除模板消息;
//                        $app_id = $payload['AuthorizerAppid'];
//                        $wechat = Wechat::where("app_id", $app_id)->first();
//                        $wechat->auth_status = -1;
//                        if (!$wechat->save()) {
//                            Log::error("WechatController notifyAuth(): Error unauthorized authorizer: $app_id: ");
//                        }
                        
                        TerminateTask::addTaskFnList(function () use ($service, $payload) {
                            $service->unauthorized($payload);
                        });
                        break;
                    case '':
                        break;
                }
            }
        });
        return $server->serve();
    }

    /**
     * 消息处理
     * @hideFromAPIDocumentation
     */
    public function notifyMsg(WechatService $service, $appId)
    {
        $open_platform = WechatOpenPlatformTool::getInstance()->getOpenPlatformApp();
        $server = $open_platform->server;
        try {
            $payload = $server->getMessage();
            // NOT: $app = EasyWeChat::openPlatform()->miniProgram($app_id, $authorizerRefreshToken);
            // $msg = $app->server->getMessage();
            //Log::notice("WechatController notifyMsg($appId): payload:", $payload);
            if (isset($payload['MsgType'])) {
                switch ($payload['MsgType']) {
                    case 'TEXT':
                        //文本消息
                        if ($payload->ToUserName == WXUSERNAME && $payload->Content == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
                            $message = new Raw('<xml>
                    <ToUserName><![CDATA[toUser]]></ToUserName>
                    <FromUserName><![CDATA[fromUser]]></FromUserName>
                    <CreateTime>12345678</CreateTime>
                    <MsgType><![CDATA[Te]]></MsgType>
                    <Image>
                    <MediaId><![CDATA[media_id]]></MediaId>
                    </Image>
                    </xml>');
                            return $message;

                        }
                        break;
                    case "LOCATION": // 微信全网event检测
                        $contentStr = $payload->Event . "from_callback";
                        return $contentStr;
                        break;
                    case 'SCAN':
                        //扫码事件
                        return "扫码事件";
                        break;
                    case 'event':
                        \App\Http\Middleware\TerminateTask::addTaskFnList(function () use ($service, $appId, $payload) {
                            $service->eventDeal($appId, $payload);
                        });
                        break;
                    default:
                        break;
                }
            }
        } catch (\Exception $e) {
            Log::error("Exception in WechatController::notifyMsg($appId)");
            Log::error( $e->getTraceAsString());
        }

        return $server->serve();
    }
    
    /**
     * 提供给本地开发token使用,见 @see \EasyWeChat\Kernel\AccessToken::getToken()
     */
    public function getToken(Request $request) {
        //进行ip访问限制
        if (!in_array($request->getClientIp(), [
            '120.36.249.216',//公司ip
        ])) {
            return $this->error('请求ip错误，无权获取', 401);
        }
        
        $openPlatform = \App\Commons\WechatOpenPlatform\WechatOpenPlatformTool::getInstance()->getOpenPlatformApp();
        
        return $this->success($openPlatform['verify_ticket']->getTicket());
    }
    
    /**
     * 授权回调
     *
     * @param Request       $request
     * @param WechatService $service
     *
     * @return mixed
     */
    public function authorizationCallback(Request $request, WechatService $service) {
        $appProjectId = $request->input('id');
        $wxAuthCode   = $request->input('auth_code');
        $expiresIn    = $request->input('expires_in');
    
        try {
            $service->getAuthInfo($appProjectId, $wxAuthCode);
            echo "<h1 style='text-align: center;margin: 30px;'>授权成功</h1>";
        } catch (\Exception $e) {
            Log::error("授权失败");
            Log::error($e->getTraceAsString());
            echo
<<<EOF
    <div style='text-align: center;'>
        <h1 style='margin: 30px;color: red;'>授权失败</h1>
        <h2>请正确查看授权是否全部勾选，将权限全部勾选；</h2>
        <h2>设置小程序命名(名称)等信息；</h2>
    </div>
EOF;
        }
    }
}